
package com.dps.omc.action;

import java.beans.IntrospectionException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dps.common.utils.*;
import com.dps.omc.enumer.EnumGroupType;
import com.dps.omc.enumer.EnumTeam;
import com.dps.omc.model.*;
import com.dps.omc.task.message.DesUtils;
import com.dps.omc.utils.excel.FieldNameAndType;
import com.dps.omc.utils.excel.ParseExcelSheetToList;
import com.dps.omc.utils.excel.export.ExportExcelService;
import com.dps.omc.utils.server.ServerConnect;
import com.dps.omc.utils.server.ServerManager;

import com.dps.omc.service.*;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dps.common.domain.view.BizData4Page;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class ServerAction extends AbstractAdminController<IServerService>{

    @Autowired
    private IServerService serverService;
    @Autowired
    private IGroupTypeService groupTypeService;
    @Autowired
    private IBizTypeService bizTypeService;
    @Autowired
    private IAgentService agentService;
    @Autowired
    private IAgentNodeService agentNodeService;
    @Autowired
    private ISystemRankService systemRankService;
    @Autowired
    private IOsTypeService osTypeService;
    @Autowired
    private ExportExcelService exportExcelService;
    @Autowired
    private ServerManager serverManager;
    
    @RequestMapping(value="/server/list")
    public String list(Server server, ModelMap model, PageParam pageParam, HttpServletRequest request, HttpServletResponse response){

        //获取参数
    	Map<String, Object> conditions = getQueryMap(server); 	
    	BizData4Page<Server> pageCtx = doPage(model, conditions, pageParam);
    	model.addAttribute("server", server);
    	return "/module/server/list";
    }    
    
    @RequestMapping(value="/server/add")
    public String add(ModelMap model,HttpServletRequest request,HttpServletResponse response){

        List<GroupType> groupTypes = groupTypeService.findAll();
        List<BizType> bizTypes = bizTypeService.findAll();
        List<Agent> agents = agentService.findAll();
        List<SystemRank> systemRanks = systemRankService.findAll();
        List<OsType> osTypes = osTypeService.findAll();

        model.addAttribute("groupTypes", groupTypes);
        model.addAttribute("bizTypes", bizTypes);
        model.addAttribute("agents", agents);
        model.addAttribute("systemRanks", systemRanks);
        model.addAttribute("osTypes", osTypes);
        model.addAttribute("teams", EnumTeam.values());
    	model.addAttribute("server", new Server());
        return "module/server/edit";
    }    
    
    @RequestMapping(value="/server/edit")
    public String edit(String id,ModelMap model,HttpServletRequest request,HttpServletResponse response){

        List<GroupType> groupTypes = groupTypeService.findAll();
        List<BizType> bizTypes = bizTypeService.findAll();
        List<Agent> agents = agentService.findAll();
        List<SystemRank> systemRanks = systemRankService.findAll();
        List<OsType> osTypes = osTypeService.findAll();

        model.addAttribute("groupTypes", groupTypes);
        model.addAttribute("bizTypes", bizTypes);
        model.addAttribute("agents", agents);
        model.addAttribute("systemRanks", systemRanks);
        model.addAttribute("osTypes", osTypes);
        model.addAttribute("teams", EnumTeam.values());
    	Server server = serverService.fetch(id);
    	model.addAttribute("server", server);
        return "module/server/edit";
    }    
    
    @RequestMapping(value="/server/save")
    @ResponseBody
    public String save(HttpServletRequest request,Server server){
		boolean isAddNew = StringUtils.isBlank(server.getId())?true:false;
		if(isAddNew)
		{
			server.setId(IdGenerator.createNewId());
            server.setGroupType(EnumGroupType.SERVER);
			serverService.add(server);
		}
		else
		{
            server.setGroupType(EnumGroupType.SERVER);
            serverService.update(server);
		}
        Agent agent = agentService.fetch(server.getAgentId());

        agentNodeService.createByServer(agent,server);
        return JsonResult.saveSuccessClose(Constants.MAIN_TAB).toString();
    }    
    
    @RequestMapping(value="/server/delete")
    @ResponseBody
    public String delete(String ids,HttpServletRequest request){
    	
    	serverService.deleteByIds(ids);
    	return JsonResult.DELETE_SUCCESS.toString();
    }

    @RequestMapping(value="/server/excel/import")
    @ResponseBody
    public String excelImport(@RequestParam("file") MultipartFile file,HttpServletRequest request) throws Exception {

        InputStream inputStream = file.getInputStream();
        FieldNameAndType[] nameAndTypes = new FieldNameAndType[13];
        nameAndTypes[0] = new FieldNameAndType("id", String.class);
        nameAndTypes[1] = new FieldNameAndType("alias", String.class);
        nameAndTypes[2] = new FieldNameAndType("agentId", String.class);
        nameAndTypes[3] = new FieldNameAndType("groupType", EnumGroupType.class);
        nameAndTypes[4] = new FieldNameAndType("bizTypeId", String.class);
        nameAndTypes[5] = new FieldNameAndType("bizTypeName", String.class);
        nameAndTypes[6] = new FieldNameAndType("opSystem", String.class);
        nameAndTypes[7] = new FieldNameAndType("sysRank", String.class);
        nameAndTypes[8] = new FieldNameAndType("host", String.class);
        nameAndTypes[9] = new FieldNameAndType("user", String.class);
        nameAndTypes[10] = new FieldNameAndType("pass", String.class);
        nameAndTypes[11] = new FieldNameAndType("note", String.class);
        nameAndTypes[12] = new FieldNameAndType("team", EnumTeam.class);
//        nameAndTypes[12] = new FieldNameAndType("createDate", Date.class);
        ParseExcelSheetToList<Server> parseExcelSheetToList = new ParseExcelSheetToList<Server>(inputStream,
                Server.class, nameAndTypes);
        List<Server> servers = parseExcelSheetToList.getList();
        for(Server server:servers)
        {
            server.setPass(DesUtils.encrypt(server.getPass()));
            if(StringUtils.isNotBlank(server.getId()))
            {
                serverService.update(server);
                Agent agent = agentService.fetch(server.getAgentId());

                agentNodeService.createByServer(agent,server);
            }
            else
            {
                serverService.add(server);
                Agent agent = agentService.fetch(server.getAgentId());

                agentNodeService.createByServer(agent,server);
            }
        }
        return JsonResult.operateSuccess(Constants.MAIN_TAB).toString();
    }

    @RequestMapping(value="/server/excel/export")
    public void excelExport(String ids,HttpServletRequest request,HttpServletResponse response) throws InvocationTargetException, IntrospectionException, IllegalAccessException, IOException {

        List<Server> servers = serverService.findByIds(ids);
        String[] title = { "id","alias","agentId","groupType" ,"bizTypeId","bizTypeName","opSystem","sysRank","host","user","pass","note","team"};
        String[] value = { "id","alias","agentId","groupType" ,"bizTypeId","bizTypeName","opSystem","sysRank","host","user","pass","note","team"};
        String sheet = "server";
        String dir = DateUtils.currentDate();
        String fileName = "server";
        String f = exportExcelService.generateExcel(dir,fileName,servers,title,value,sheet,false);
        File file = new File(f);
        InputStream input = FileUtils.openInputStream(file);
        byte[] data = IOUtils.toByteArray(input);

        String fn = URLEncoder.encode(file.getName(), "UTF-8");

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fn + "\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IOUtils.write(data, response.getOutputStream());
        IOUtils.closeQuietly(input);
//        return JsonResult.operateSuccess(Constants.MAIN_TAB).toString();
    }

    protected Map getQueryMap(Server server)
    {
    	Map<String, Object> conditions = new HashMap();
    	
		conditions.put("alias", server.getAlias());		
		conditions.put("agentId", server.getAgentId());		
		conditions.put("groupType", server.getGroupType());		
		conditions.put("bizTypeId", server.getBizTypeId());		
		conditions.put("bizTypeName", server.getBizTypeName());		
		conditions.put("opSystem", server.getOpSystem());		
		conditions.put("sysRank", server.getSysRank());		
		conditions.put("host", server.getHost());		
		conditions.put("user", server.getUser());		
		conditions.put("pass", server.getPass());		
		conditions.put("note", server.getNote());		
		conditions.put("createDate", server.getCreateDate());		
    	return conditions;
    }

    //測試連接
    @RequestMapping(value="/server/testconnect")
    @ResponseBody
    public String testConnect(HttpServletRequest request) throws Exception {

        String opSystem = request.getParameter("opSystem");
        String host = request.getParameter("host");
        String user = request.getParameter("user");
        String pass = request.getParameter("pass");
        pass = DesUtils.decrypt(pass);

        ServerConnect serverConnect = new ServerConnect();
        serverConnect.setOpSystem(opSystem);
        serverConnect.setHost(host);
        serverConnect.setUser(user);
        serverConnect.setPass(pass);
        return serverManager.testConnect(serverConnect);
    }


    @Override
    protected IServerService getMainService() {
        return serverService;
    }

    @Override
    protected String getMainObjName() {
        return "server";
    }

    @Override
    protected String getViewTitle() {
        return "server";
    }
}
